<?php
/**
 * Created by PhpStorm.
 * User: lili
 * Date: 2018/11/16
 * Time: 20:19
 */

namespace app\index\controller;




use app\index\model\Baseinsulin;
use app\index\model\Beginningtreatment;
use app\index\model\Item;
use app\index\model\Reason;
use app\index\model\Sulintime;
use app\index\model\User;
use app\index\validate\Check;
use think\Validate;
use Tools\Utf8ToPinyin;

class Treat extends Common
{

    /*
     * 增加起始治疗方案
     *
     *
     * */
    public function Treatment(){

        if (request()->isPost()){
            $send = input('post.','','htmlspecialchars,strip_tags,trim');

            $btv = new \app\index\validate\Beginningtreatment();
            if ($btv->check($send)){
                $uid = $send['uid'];
                $btmodel = new Beginningtreatment();
                $w['uid'] = $uid;
                unset($send['token']);
                $usermodel = new User();
                if($usermodel->isUser($w)){
                    if ($btmodel->isHaving($w)){
                        //存在更新
//                        dump($send);
                        $res = $btmodel->isUpdate(true)->save($send,[
                            'uid' => $uid
                        ]);
                        if($res!=false){
                            $bimodel = new Baseinsulin();
                            $bimodel->insertbaseinsulin($uid,$send['baseinsulin'],time());//插入基础率总量修改记录
                            $stmodel = new Sulintime();
                            $stmodel->insertSulintime($uid,$send['sulin0003'],$send['sulin0307'],$send['sulin0712'],$send['sulin1217'],$send['sulin1722'],$send['sulin2224'],time());//插入基础率总量修改记录
                            rjson(100,'更新成功');
                        }
                    }else{
                        //增加
                        $res = $btmodel->isUpdate(false)->save($send);
                        if($res!=false){
                            $bimodel = new Baseinsulin();
                            $bimodel->insertbaseinsulin($uid,$send['baseinsulin'],time());//插入基础率总量修改记录
                            $stmodel = new Sulintime();
                            $stmodel->insertSulintime($uid,$send['sulin0003'],$send['sulin0307'],$send['sulin0712'],$send['sulin1217'],$send['sulin1722'],$send['sulin2224'],time());//插入总量修改记录
                            rjson(100,'增加成功');
                        }
                    }
                }else{
                    rjson(110,'不存在这个用户');
                }

            }else{
                rjson(110,$btv->getError());
            }
        }else{
            rjson(110,'必须post请求');
        }

    }







    /*
     * 获得血糖监测的items
     * 例如，输入血糖的id=1，输入睡前，凌晨等等的id和子items信息，递归获得
     * @param int $pid 父级id
     * @return json 递归的父级以及子孙items
     * */
    public function getItemsmsg(){

        $send = input();

        $rules = [
            'pid'  => 'require|number'
        ];
        $msg = [
            'pid.require' => 'pid参数缺失',
            'pid.number' => 'pid为整数',

        ];
        $validate = new Validate($rules,$msg);
        if($validate->check($send)){

            $itemmodel = new Item();
            $items = $itemmodel->getItems($send['pid']);

            rjson(100,'监测输入选择项目',$items);

        }else{
            rjson(110,$validate->getError());
        }



        
    }



    /*
     * 记录血糖或者大剂量
     * @param int $uid 用户id
     * @param int $pid 父级id 例如血糖id，或者餐前大剂量id
     * @param int $itemid 子类id 例如早餐前id
     * @param string $date 录入的时间，例如 '2018-11-17 16:59:33'
     * @param float $value 血糖的值或大剂量的值
     * */
    public function setcheck(){
        

        
        if(request()->isPost()){

            $send = input();
            unset($send['token']);
            $checkv = new Check();
            $checkres = array();

            if($checkv->check($send)){
                if($send['pid']==1){
                    $checkmodel = new \app\index\model\Check();


                 /*   $lastcheck = $checkmodel->getLastCheck($send['uid'],$send['pid'] , $send['date']);
                    if (!empty($lastcheck)){
                        $value = $lastcheck['value'];
                    }*/

                    if ( in_array($send['itemid'],array(6,8,10) )  ){
                        //空腹
                    }else{
                        //非空腹
                    }
                     
                    $health = 1;//健康
                    $checkres['type'] = 3;//正常
                    /*if (!empty($value)){
                        if($send['value']<4.4){
                            if($send['value']<$value*0.7){
                                $health = 3;//跳问题框，给与风险警告
                            }else{
                                $health = 2;//给与风险提示
                            }
                            $checkres['type'] = 1;//低
                        }else if($send['value']>11.1){
                            if($send['value']>$value*1.3){
                                $health = 3;//跳问题框，给与风险警告
                            }else{
                                $health = 2;//给与风险提示
                            }
                            $checkres['type'] = 2;//高
                        }
                    }else{*/

                        if($send['value']<4.4){
                            if($send['value']<3.9){
                                $health = 3;//低血糖警告

                            }else{
                                $health = 2;//低血糖提示
                            }
                            $checkres['type'] = 1;//低

                        }else if($send['value']>11.1){

                            if($send['value']>16.7){
                                $health = 5;//高血糖警报
                            }else{
                                $health = 4;//高血糖提示
                            }
                            $checkres['type'] = 2;//高

                        }
//                    }

                    $send['health'] = $health;//高
                    $send['type'] = $checkres['type'];//健康指数
                    $send['itemid'] = implode(',',array($send['pid'],$send['itemid']) );
                    $checkres['health'] = $health;//高
                    $checkres['send'] = $send;//存进数据库的数据
                    unset($send['pid']);

                    $res = $checkmodel->isUpdate(false)->save($send);
                    if($res!=false){
                        $checkres['cid'] = $checkmodel->cid;
                        rjson(100,'血糖录入成功',$checkres);
                    }





                }else{
                    $checkres = $send;

                    if(!empty($send['itemid'])){
                        $send['itemid'] = implode(',',array($send['pid'],$send['itemid']) );
                    }
                    unset($send['pid']);
                    if(!empty($send['itemid'])){
                        $checkres['itemid'] = $send['itemid'];
                    }
                    
                    $checkmodel = new \app\index\model\Check();


                    $c = $checkmodel->where('itemid' ,'eq',$send['itemid'])->where('date','like','%'.$send['date'].'%')->find();
                    if (empty($c)){
                        //没有数据，插入
                        $res = $checkmodel->isUpdate(false)->save($send);
                        if($res!=false){
                            $checkres['cid'] = $checkmodel->cid;
                            rjson(100,'录入成功',$checkres);
                        }
                    }else{
                        //有数据，更新
                        $res = $checkmodel->isUpdate(true)->save($send,[
                            'cid'=>$c['cid'],
                        ]);
                        if($res!=false){
                            $checkres['cid'] = $c['cid'];
                            rjson(100,'更新',$checkres);
                        }
                    }




                }

            }else{
                rjson(110,$checkv->getError());
            }
        }else{
            rjson(110,'必须post请求');
        }
    }




    /*
     * 获得起始治疗方案
     * @param int uid 用户id
     *
     *
     * */
    public function getTreatment(){
        $uid = input('uid');
        if(empty($uid)){
            rjson(110,'uid不可以为空');
        }
        $btmodel = new Beginningtreatment();
        $res = $btmodel->where('uid',$uid)->find();
        if (!empty($res)){
            rjson(100,'起始治疗方案',$res);
        }else{
            rjson(110,'没有该数据');
        }
    }


    /*
     * 当天胰岛素的使用情况
     * @param int uid 用户id
     *
     * */
    public function getinsulinoftoday(){
        $uid = input('uid');
        if(empty($uid)){
            rjson(110,'uid不可以为空');
        }
        $btmodel = new Beginningtreatment();
        $checkmodel = new \app\index\model\Check();
        $res = $btmodel->where('uid',$uid)->find();
        $baseinsulintoday = $res['baseinsulin'];//基础率总量
        $beforeeatinsulintoday = $checkmodel->getbeforeeatinsulinOfToday($uid);//今天的餐前大剂量总量
        $temporaryinsulintoday = $checkmodel->gettemporaryinsulinOfToday($uid);//今天的临时大剂量总量
        
        $temporaryinsulinlisttoday = $checkmodel->gettemporaryinsulinListOfToday($uid);//今天的临时大剂量列表
        $insulintoday = $baseinsulintoday + $beforeeatinsulintoday + $temporaryinsulintoday;//今天的总量

        $insulintodayarr = array(
            'baseinsulintoday' => $baseinsulintoday,
            'beforeeatinsulintoday' => $beforeeatinsulintoday,
            'temporaryinsulintoday' => $temporaryinsulintoday,
            'temporaryinsulinlisttoday' => $temporaryinsulinlisttoday,
            'insulintoday' => number_format($insulintoday,2)  

        );

        rjson(100,'当天胰岛素使用情况',$insulintodayarr);



    }


    /*
     * 历史记录胰岛素的使用情况
     * @param int uid 用户id
     * @param int date 时间
     * */
    public function getinsulinoftdate(){
        $uid = input('uid');
        $date = input('date');
        if(empty($uid)){
            rjson(110,'uid不可以为空');
        }
        if (empty($date)){
            rjson(110,'date不可以为空');
        }
        $btmodel = new Beginningtreatment();
        $checkmodel = new \app\index\model\Check();
        $res = $btmodel->where('uid',$uid)->find();
        $baseinsulinDate = $res['baseinsulin'];//基础率总量
        $beforeeatinsulinDate = $checkmodel->getbeforeeatinsulinOfDate($uid,$date);//历史记录的餐前大剂量总量
        $temporaryinsulinDate = $checkmodel->gettemporaryinsulinOfDate($uid,$date);//历史记录的临时大剂量总量
        $temporaryinsulinlistDate = $checkmodel->gettemporaryinsulinListOfDate($uid,$date);//历史记录的临时大剂量列表
        $insulinDate = $baseinsulinDate + $beforeeatinsulinDate + $temporaryinsulinDate;//历史记录的总量

        $insulindatearr = array(
            'baseinsulindate' => $baseinsulinDate,
            'beforeeatinsulindate' => $beforeeatinsulinDate,
            'temporaryinsulindate' => $temporaryinsulinDate,
            'temporaryinsulinlistdate' => $temporaryinsulinlistDate,
            'insulindate' => number_format($insulinDate,2)  

        );

        rjson(100,'当天胰岛素使用情况',$insulindatearr);



    }



    /*
     * 历史记录血糖的使用情况
     * @param int uid 用户id
     * @param int date 时间
     *
     *
     * */
    public function getBloodSugerlistofDate(){
        $uid = input('uid');
        $date = input('date');
        if(empty($uid)){
            rjson(110,'uid不可以为空');
        }
        if (empty($date)){
            rjson(110,'date不可以为空');
        }
        $checkmodel = new \app\index\model\Check();
        $bsres = $checkmodel->getBloodSugarCheckOfDate($uid, $date);
        $res2 = array() ;//中文转拼音
        $pinyin = new Utf8ToPinyin();
//        echo  $pinyin->encode('夜间3点');
        foreach ($bsres as $i => $v){
            $res2[trimall($pinyin->encode($i,'all'))] = $v;

        }

        rjson(100,'历史记录血糖的使用情况',$res2);
    }


    /*
     * 历史餐前大剂量的列表使用情况
     * @param int uid 用户id
     * @param int date 时间
     *
     *
     * */
    public function getBeforeeatingListofDate(){
        $uid = input('uid');
        $date = input('date');
        if(empty($uid)){
            rjson(110,'uid不可以为空');
        }
        if (empty($date)){
            rjson(110,'date不可以为空');
        }
        $checkmodel = new \app\index\model\Check();
        $bsres = $checkmodel->getBeforeeatingListOfDate($uid, $date);

        $res2 = array() ;//中文转拼音
        $pinyin = new Utf8ToPinyin();
//        echo  $pinyin->encode('夜间3点');
        foreach ($bsres as $i => $v){
            $res2[trimall($pinyin->encode($i,'all'))] = $v;
        }
        
        rjson(100,'餐前大剂量列表的使用情况',$res2);
    }

    /*
         * 历史临时大剂量的列表使用情况
         * @param int uid 用户id
         * @param int date 时间
         *
         *
         * */
    public function gettemporaryinsulinListofDate(){
        $uid = input('uid');
        $date = input('date');
        if(empty($uid)){
            rjson(110,'uid不可以为空');
        }
        if (empty($date)){
            rjson(110,'date不可以为空');
        }
        $checkmodel = new \app\index\model\Check();
        $bsres = $checkmodel->gettemporaryinsulinListOfDate($uid, $date);

        $res2 = array() ;//中文转拼音
        $pinyin = new Utf8ToPinyin();
//        echo  $pinyin->encode('夜间3点');
        foreach ($bsres as $i => $v){
            $res2[trimall($pinyin->encode($i,'all'))] = $v;

        }
        rjson(100,'临时大剂量列表的使用情况',$res2);
    }

    /*
     * 删除胰岛素记录或者血糖记录
     *  @param int cid 记录主键id
     *
     * */
    public function delCheck(){
        $cid = input('cid');
        $checkmodel = new \app\index\model\Check();
        $c = $checkmodel->where('cid',$cid)->find();
        if(!empty($c)){
            $res = $checkmodel->destroy($cid);
            if($res!=false){
                rjson(100,'删除成功',$c);
            }
        }else{
            rjson(110,'删除数据不存在');
        }
    }






    /*
     *
     * 获得胰岛素剂量记录或者血糖记录
     *
     *
     * */
    public function getCheck(){
        $cid = input('cid');
        $checkmodel = new \app\index\model\Check();
        $c = $checkmodel->where('cid',$cid)->find();
        if(!empty($c)){
            $c['time'] = date('H:i',strtotime($c['date']));

            $itemidsarr = explode(',',$c['itemid'] );
            $itemmodel = new Item();

            $itemid = $itemidsarr[0];
            $item = $itemmodel->where('itemid',$itemid)->find();
            $c['pitemname'] = $item['itemname'];//一级项目名称
            $c['pid'] = $itemid;//一级项目id

            $itemid = $itemidsarr[1];
            $item = $itemmodel->where('itemid',$itemid)->find();
            $c['itemname'] = $item['itemname'];//二级项目名称
            $c['itemid'] = $itemid;//二级项目id

            if (!empty($c['reasonid'])){
                $reasonmodel = new Reason();
                $reasonlist = $reasonmodel->where('rid','in',$c['reasonid'])->select();
                $c['reasonlist'] = $reasonlist;
            }


            rjson(100,'获得成功',$c);

        }else{
            rjson(110,'数据不存在');
        }
    }



    /*
     * 修改胰岛素剂量或者血糖值
     *
     *
     * */
    public function modifycheck(){
        if(request()->isPost()){

            $send = input();
            unset($send['token']);
            $checkv = new Check();
            $checkres = array();
            $cid = input('cid');

            if($checkv->check($send)){
                if($send['pid']==1){
                    $checkmodel = new \app\index\model\Check();
                   /* $lastcheck = $checkmodel->getLastCheck($send['uid'],$send['pid'] , $send['date']);
                    if (!empty($lastcheck)){
                        $value = $lastcheck['value'];
                    }

                    if ( in_array($send['itemid'],array(6,8,10) )  ){
                        //空腹
                    }else{
                        //非空腹
                    }*/

                    $health = 1;//健康
                    $checkres['type'] = 3;//正常
                    /*if (!empty($value)){
                        if($send['value']<4.4){
                            if($send['value']<$value*0.7){
                                $health = 3;//跳问题框，给与风险警告
                            }else{
                                $health = 2;//给与风险提示
                            }
                            $checkres['type'] = 1;//低
                        }else if($send['value']>11.1){
                            if($send['value']>$value*1.3){
                                $health = 3;//跳问题框，给与风险警告
                            }else{
                                $health = 2;//给与风险提示
                            }
                            $checkres['type'] = 2;//高
                        }
                    }else{*/

                        if($send['value']<4.4){
                            if($send['value']<3.9){
                                $health = 3;//低血糖警告

                            }else{
                                $health = 2;//低血糖提示
                            }
                            $checkres['type'] = 1;//低

                        }else if($send['value']>11.1){

                            if($send['value']>16.7){
                                $health = 5;//高血糖警报
                            }else{
                                $health = 4;//高血糖提示
                            }
                            $checkres['type'] = 2;//高

                        }
//                    }

                    $send['health'] = $health;//高
                    $send['type'] = $checkres['type'];//健康指数
                    $send['itemid'] = implode(',',array($send['pid'],$send['itemid']) );
                    $checkres['health'] = $health;//高
                    $checkres['send'] = $send;//存进数据库的数据
                    unset($send['pid']);

                    $res = $checkmodel->isUpdate(true)->save($send,['cid'=>$cid]);
                    if($res!=false){
                        $checkres['cid'] = $checkmodel->cid;
                        rjson(100,'血糖更新成功',$checkres);
                    }





                }else{
                    $checkres = $send;

                    if(!empty($send['itemid'])){
                        $send['itemid'] = implode(',',array($send['pid'],$send['itemid']) );
                    }
                    unset($send['pid']);
                    if(!empty($send['itemid'])){
                        $checkres['itemid'] = $send['itemid'];
                    }

                    $checkmodel = new \app\index\model\Check();
                    $res = $checkmodel->isUpdate(true)->save($send,['cid'=>$cid]);
                    if($res!=false){
                        $checkres['cid'] = $checkmodel->cid;
                        rjson(100,'更新成功',$checkres);
                    }
                }

            }else{
                rjson(110,$checkv->getError());
            }
        }else{
            rjson(110,'必须post请求');
        }
    }


    /*
     * 获得血糖不正常的原因列表
     * @param int type 1低血糖，2高血糖
     *
     * */
    public function getReasonbyType(){
        $type = input('type');

        $reasonmodel = new Reason();
        $reasonlist = $reasonmodel->where('type',$type)->select();//原因列表

        if (!empty($reasonlist)){
            rjson(100,'血糖不正常原因列表',$reasonlist);
        }else{
            rjson(110,'找不到结果');
        }
        
        
    }


    /*
     * 对于高血糖或者低血糖录入原因
     * @param string reasonid reson表的id，字符串，逗号隔开，如1,2
     * @param int cid 血糖记录的cid
     * @param string reason 其他原因
     * */
    public function addBloodReason(){
        $reasonid = input('reasonid');
        $cid = input('cid');
        $reason = input('reason');
        if (!empty($reason)){
           
            $data['reason'] = $reason;
        }

        $data['reasonid'] = $reasonid;


        $checkmodel = new \app\index\model\Check();
        $res = $checkmodel->isUpdate(true)->save($data,['cid'=>$cid]);
        if ($res!=false){
            rjson(100,'原因录入成功');
        }else{
            rjson(110,'录入失败');
        }
    }


    /*
     * 获得血糖/胰岛素历史记录，最后那个历史记录列表页面
     * @param date sdate 开始的时间 例如 2018-12-05
     * @param date edate 结束的时间 例如 2018-12-07
     * @param int uid 用户id
     * @param string  itemnamestr  时段筛选 '早餐前,早餐后,午餐前'
     *
     *
     *
     * */
    public function getHistoryList(){

        $send = input();
        if (empty($send['uid'])){
            rjson(110,'uid缺失');
        }
        if (empty($send['sdate'])){
            rjson(110,'开始时间缺失');
        }
        if (empty($send['edate'])){
            rjson(110,'结束时间缺失');
        }


        $resarrall = array();//返回的数组

        $uid = $send['uid'];
        //基础率时分段设计
        $btmodel = new Beginningtreatment();
        



        $sdatetime = strtotime($send['sdate']);//开始时间
        $sdatetime =  strtotime(date('Y-m-d',$sdatetime)) ;//0点时间戳

        $edatetime = strtotime($send['edate']);//结束时间
        $edatetime =  strtotime(date('Y-m-d',$edatetime)) ;//0点时间戳

        while($sdatetime<=$edatetime){

            $btttmsg =  $btmodel->getBTByUid($send['uid'],$sdatetime);//起始治疗方案数据，里面有  基础率时分段设计

            $sdate = date('Y-m-d',$sdatetime);//格式化时间
            
            $checkmodel = new \app\index\model\Check();

//            $bfesum = $checkmodel->getbeforeeatinsulinOfDate($uid, $sdate);//餐前大剂量总量
            $baseinsulin = $btttmsg['baseinsulin'];//基础率总量

            $beforeeatinsulinDate = $checkmodel->getbeforeeatinsulinOfDate($uid,$sdate);//历史记录的餐前大剂量总量
            $temporaryinsulinDate = $checkmodel->gettemporaryinsulinOfDate($uid,$sdate);//历史记录的临时大剂量总量
            $insulinDate = $baseinsulin + $beforeeatinsulinDate + $temporaryinsulinDate;//历史记录的总量



            $bfel = $checkmodel->getBeforeeatingListOfDate($uid, $sdate);//餐前大剂量列表

            $bsl = $checkmodel->getBloodSugarCheckOfDate($uid, $sdate);//血糖列表
            $bsllast = $checkmodel->getBloodSugarCheckOfDate($uid, date('Y-m-d',strtotime('-1day',$sdatetime )) );//血糖列表


            $ipw = $checkmodel->getInsulinPiecewise($btttmsg,$bfel,$bsl,$bsllast);//当天胰岛素分段量
//            dump($bsl);
//            dump($ipw);
//            dump($baseinsulin);
//            dump($beforeeatinsulinDate);
//            dump($temporaryinsulinDate);
//            dump($insulinDate);


            $resarr = array();
            $resarr['date'] = date('m.d',$sdatetime);//时间日期
            $resarr['datetime'] = date('Y-m-d',$sdatetime);//时间日期
            $resarr['insulinDate'] =number_format($insulinDate,2) ;//胰岛素总量
            $resarr['baseandbeforeeatin'] =   array(  // 基础总/餐前总
                'baseinsulin'=>$baseinsulin,//基础率总量
                'beforeeatinsulinDate'=>$beforeeatinsulinDate,//餐前大剂量总量
            );


            $pinyin = new Utf8ToPinyin();//拼音类

            if (!empty($send['itemnamestr'])){
                $itemnamearr = explode(',',$send['itemnamestr'] );//转成数组
                foreach ($ipw as $ii => $iv){
                    if (in_array($ii, $itemnamearr)){//字段筛选
                        $resarr[trimall($pinyin->encode($ii,'all'))] = array() ;
                        $resarr[trimall($pinyin->encode($ii,'all'))]['bs'] = $bsl[$ii];//血糖值
                        $resarr[trimall($pinyin->encode($ii,'all'))]['insulin'] = $ipw[$ii];//胰岛素分段值
                    }
                }
            }else{
                foreach ($ipw as $ii => $iv){
                    $resarr[trimall($pinyin->encode($ii,'all'))] = array() ;
                    $resarr[trimall($pinyin->encode($ii,'all'))]['bs'] = $bsl[$ii];//血糖值
                    $resarr[trimall($pinyin->encode($ii,'all'))]['insulin'] = $ipw[$ii];//胰岛素分段值
                }
            }



//            dump($resarr);
            $resarrall[]  = $resarr;



            $sdatetime = strtotime('+1day',$sdatetime);//时间戳+1day


        }

        rjson(100,'记录',$resarrall);







    }

    
}